﻿using UnityEditor;
using UnityEngine;

[CustomEditor(typeof(HK_Path))]
public class HK_PathEditor : Editor
{
    void OnSceneGUI()
    {
        HK_Path path = (HK_Path)target;

        if (path.wayPoints.Count == 0)
            return;

        // 用 Handle 绘制路径点并允许用户拖动它们
        for (int i = 0; i < path.wayPoints.Count; i++)
        {
            EditorGUI.BeginChangeCheck();

            Vector3 oldPoint = path.wayPoints[i];

            Vector3 newPoint = Handles.PositionHandle(oldPoint, Quaternion.identity);

            if (EditorGUI.EndChangeCheck())
            {
                Undo.RecordObject(path, "Move Path Point");
                path.wayPoints[i] = newPoint;

                path.wayPointsOffset[i] = newPoint - path.transform.position;

                EditorUtility.SetDirty(path);
            }
        }

        // 绘制连接路径点的线段
        Handles.color = Color.green;

        for (int i = 0; i < path.wayPoints.Count - 1; i++)
        {
            Handles.DrawLine(path.wayPoints[i], path.wayPoints[i + 1]);
        }

        if (Handles.Button(path.wayPoints[path.wayPoints.Count - 1], Quaternion.identity, 0.1f, 0.1f, Handles.SphereHandleCap))
        {
            Undo.RecordObject(path, "Add Path Point");
            Vector3 newPoint = path.wayPoints[path.wayPoints.Count - 1] + Vector3.right;
            path.wayPoints.Add(newPoint);
            EditorUtility.SetDirty(path);
        }
    }

    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();

        if (GUILayout.Button("Add Waypoint"))
        {
            AddWaypoint();
        }

        if (GUILayout.Button("Clear Waypoints"))
        {
            ClearWayPoints();
        }
    }

    void AddWaypoint()
    {
        HK_Path path = (HK_Path)target;

        Undo.RecordObject(path, "Add Waypoint");
        if (path.wayPoints.Count > 0)
        {
            Vector3 newPoint = path.wayPoints[path.wayPoints.Count - 1] + Vector3.right;
            path.wayPointsOffset.Add(path.wayPoints[0] - path.transform.position);

            path.wayPoints.Add(newPoint);
            EditorUtility.SetDirty(path);
        }
        else
        {
            path.wayPoints.Add(path.transform.position);
        }
        EditorUtility.SetDirty(path);
    }

    void ClearWayPoints()
    {
        HK_Path path = (HK_Path)target;

        Undo.RecordObject(path, "Clear Waypoints");
        path.wayPoints.Clear();
        EditorUtility.SetDirty(path);
    }
}
